package vip.wangwenhao.sso.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import vip.wangwenhao.autoconfigure.constants.Oauth2Constants;
import vip.wangwenhao.common.result.Result;
import vip.wangwenhao.sso.service.TokenService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author wwh
 * @date 2019年12月30日 11:20
 */

@RestController
@RequestMapping("token")
@Slf4j
public class TokenController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private TokenStore tokenStore;

    @Resource
    @Qualifier("defaultTokenServices")
    private AuthorizationServerTokenServices authorizationServerTokenServices;

    @RequestMapping(value = "get", method = RequestMethod.POST)
    public Result<OAuth2AccessToken> getToken(HttpServletRequest request, Authentication authentication) {
        return tokenService.get(request, authentication);
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Result<JSONObject> login(HttpServletRequest request, @RequestParam(value = Oauth2Constants.ACCESS_TOKEN_QUERY_NAME, required = false) String accessToken) {
        log.info("accessToken:{}", accessToken);
        return tokenService.login(request);
    }

    @RequestMapping(value = "read", method = RequestMethod.POST)
    public Result<JSONObject> read(@RequestParam(Oauth2Constants.ACCESS_TOKEN_QUERY_NAME) String accessToken) {
        return Result.success(JSONObject.parseObject(JSONObject.toJSONString(tokenStore.readAuthentication(accessToken))));
    }
}